package org.twdata.pipeline;

import org.apache.commons.pool.BaseKeyedPoolableObjectFactory;
import org.springframework.beans.factory.*;

/**
 *  Creates pipeline stages for the instance pool by retrieving them from the
 *  Spring BeanFactory.
 */
public class PooledStageSpringFactory extends BaseKeyedPoolableObjectFactory implements BeanFactoryAware {

    private BeanFactory factory;


    /**
     *  Makes the stage by retrieving it from the bean factory
     *
     *@param  key  The key
     *@return      The object
     */
    public Object makeObject(Object key) {
        return factory.getBean((String) key);
    }


    /**
     *  Recycles the stage when it is returned to the pool
     *
     *@param  key  The key
     *@param  obj  The object
     */
    public void passivateObject(Object key, Object obj) {
        ((Stage) obj).recycle();
    }


    /**
     *  Sets the beanFactory
     *
     *@param  factory  The new beanFactory value
     */
    public void setBeanFactory(BeanFactory factory) {
        this.factory = factory;
    }
}

